package cn.wolfcode.web.interceptor;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.service.PermissionService;
import cn.wolfcode.util.RequirePermission;
import cn.wolfcode.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.util.List;

public class PermissionInterceptor implements HandlerInterceptor{

    @Autowired
    private PermissionService permissionService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws ServletException, IOException {
         //权限判断的逻辑
         //1 获取当前登录的用户
        HttpSession session = request.getSession();
        //Employee employee = (Employee) session.getAttribute("EMPLOYEE_IN_SESSION");
        Employee employee = UserContext.getCurrentUser();
        //2 判断是否为 超级管理员
        if (employee.getAdmin()){
            //是 == 放行
            return true;
        }
        //否 == 第三步
        //3 获取当前要执行的处理方法(controller照片给你具体执行的方法)
        HandlerMethod handlerMethod = (HandlerMethod)handler;
        RequirePermission methodAnnotation = handlerMethod.getMethodAnnotation(RequirePermission.class);
        //4 判断该方法是否有贴上自定义的权限注解
        if (methodAnnotation == null){
            //如果没有贴注解 == 放行
            return true;
        }
        //如果有贴注解 == 第五步
        //5 获取该方法的权限表达式(比如: department:list)
        String expression = methodAnnotation.expression();
        //6 获取当前用户已经拥有的权限表达式集合
        //List<String>   strings = (List<String>) session.getAttribute("PERMISSION_IN_SESSION");
        List<String> strings = UserContext.getPermissionExpression();

        //7 判断方法的权限表达式是否在该集合中
        if (strings.contains(expression)){
            // 如果存在就放行 == 放行
            return true;
        }
         //如果不存在 就跳转到错误页面
        request.getRequestDispatcher("/WEB-INF/views/common/nopermission.jsp").forward(request,response);
        //9 不放行
        return false;
    }
}
